/*
	#(35) - Wall
	@(64) - Is where 'we' are on the floor
	+(43) - Is where 'we' are on an empty slot
	.(46) - Is an empty sink
	*(42) - is a filled sink
	$(36) - is an out of position block
	 (32) - a blank cell, we put a space in there, is a normal cell
*/
var mapCellTypeToSprite = 
{
	"35" : "wall",
	"64" : "self",
	"46" : "empty_slot",
	"42" : "filled_slot",
	"36" : "block",
	"32" : "floor"
};

var themes = 
{
	"default" :
	{
		"wall" : "wall.png",
		"floor" : "floor.png",
		"empty_slot" : "empty_slot.png",
		"filled_slot" : "filled_slot.png",
		"self" : "self.png",
		"block" : "block.png",
	}
};
var themeInUse = "default";
var sprites = {};
var screen;

var loadedImages = 0;
function handleLoadSprite()
{
	loadedImages++;
	
	if(loadedImages == 6)
		init(1);
}
function initSprites()
{
	for(var i in themes[themeInUse])
	{
		sprites[i] = new Image();
		sprites[i].onload = handleLoadSprite;
		sprites[i].src = "images/" + themeInUse + "/" + themes[themeInUse][i];
	}
	sprites.maxWidth = sprites.width = 200;
	sprites.maxHeight = sprites.height = 200;
}

function drawSprite(type,x,y)
{
	var manToBeDrawn = 0;
	if(type == 30)
		return;
	if(type == 64)
	{
		type = 32;
		manToBeDrawn = 1;
	}
	else if(type == 43)
	{
		type = 46;
		manToBeDrawn = 1;
	}
	var sprite = sprites[mapCellTypeToSprite[type.toString()]];
	screen.drawImage(sprite,x,y,sprites.width,sprites.height);
	if(manToBeDrawn)
	{
		type = 64;
		sprite = sprites[mapCellTypeToSprite[type.toString()]];
		screen.drawImage(sprite,x,y,sprites.width,sprites.height);
	}
}

function layoutLevel()
{
	var level = game.currentLevel;
	
	var maxWidth = 0;
	for(var row = 0;row < level.length;row++)
	{
		if(maxWidth < level[row].length)
			maxWidth = level[row].length;
	}
	var maxHeight = level.length;
	
	sprites.height = sprites.width = ((screen.width / maxWidth) < (screen.height / maxHeight)) ? parseInt(screen.width / maxWidth) : parseInt(screen.height / maxHeight);
	
	screen.fillStyle = "rgb(0,0,0)";
	screen.fillRect(0,0,screen.width,screen.height);
	
	for(var row = 0;row < level.length;row++)
	{
		var floorToBeDrawn = 0;
		for(var column = 0;column < level[row].length;column++)
		{
			var type = level[row][column];
			if(type == undefined)
				type = 32;
			
			if(type != 32)
				floorToBeDrawn = 1;
			
			if(type == 32 && !floorToBeDrawn)
				continue;
			if(type == 64 || type == 43)
				game.playerPos = [row,column];
			drawSprite(type,column*sprites.height,row*sprites.width);
		}
	}
}